﻿using Carter;
using Microsoft.EntityFrameworkCore;
using TodoList.Carter.DTOs;
using TodoList.Carter.Mapper;
using TodoList.Data;

namespace TodoList.Carter.Endpoints
{
	public class TodoListModule : ICarterModule
	{
		public void AddRoutes(IEndpointRouteBuilder app)
		{
			app.MapPost("/api/todoList", async (
				ApplicationDbContext db, 
				CreateTodoItemRequest request
				) =>
			{
				var item = request.ToEntity();
				db.TodoItems.Add(item);
				await db.SaveChangesAsync();
				return Results.Created($"/todoList/{item.Id}", item);
			}).AllowAnonymous();
			
			
			app.MapDelete("/api/todolist/{id:int}", async (
				ApplicationDbContext db,
				int id) =>
			{
				var todo = await db.TodoItems.FindAsync(id);
				if (todo == null)
				{
					return Results.NotFound("Todo item not found");
				}
				db.TodoItems.Remove(todo);
				await db.SaveChangesAsync();
				return Results.Ok("Todo item deleted successfully");
			}).AllowAnonymous();
			
			app.MapGet("/api/todolist", async (
				ApplicationDbContext db
				) =>
			{
				var result = await db.TodoItems.ToListAsync();
				return Results.Ok(result);
			}).AllowAnonymous();
			
			app.MapPut("/api/todoList/{id:int}", async (
				ApplicationDbContext db,
				int id,
				UpdateTodoItemRequest request
				) =>
			{
				var todoItem = await db.TodoItems.FindAsync(id);
				if (todoItem == null)
				{
					return Results.NotFound("Todo item not found");
				}
				todoItem.UpdateEntity(request);
				db.TodoItems.Update(todoItem);
				await db.SaveChangesAsync();
				return Results.Ok("Todo item updated successfully");
			}).AllowAnonymous();
		}
	}
}
